<template>
    <div class="main-content">
        <echartsLayout :formState='formState' :dataListState='dataListState' :eCharts1State='eCharts1State' :eCharts2State='eCharts2State' 
        :eCharts3State='eCharts3State' :chartsListState='chartsListState' :tableState='tableState'>
            <div slot="form">
                <el-form :model="formInline" ref="formInline" label-width="80px">
                    <el-row :gutter="41">
                      <el-col :span="7">
                           <el-form-item label="时间范围">
                            <el-select v-model="formInline.time" placeholder="请选择时间范围" 
                            style="width:100%">
                                    <el-option v-for="(item,index) in timeArrs" 
                                    :key="index" :label="item.timeName" :value="item.timeId"> 
                                    </el-option>
                            </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="2">
                            <div class="top-line">
                                <el-button type="primary" class="btn-common" @click="submit">查询</el-button>
                            </div>
                        </el-col>
                    </el-row> 
                </el-form>
            </div> 
             <div slot="dataList" v-loading="loading1">
                <el-row :gutter="20">
                    <el-col :span="12" class="data-item">
                        <div class="item">
                            <div class="title">{{totoleAssignPerTitle}}</div>
                            <div class="data">{{totoleAssignPer}}</div> 
                        </div>
                    </el-col>
                    <el-col :span="12" class="data-item">
                        <div class="item">
                            <div class="title">{{totoleAssignNumTitle}}</div>
                            <div class="data">{{totoleAssignNum}}</div> 
                        </div>
                    </el-col> 
                </el-row>
            </div>
            <div slot="eCharts1"  v-loading="loading2">
                <div class="charts-title">提交作业汇总数据</div>
                <div class="charts-display">
                   <trendChart width='100%' height='100%' id="trendChart2" :option='pieWorkCount'></trendChart>
                </div>
            </div>
            <div slot="eCharts2"  v-loading="loading3">
                <div class="charts-title">布置课外作业TOP10</div>
                <div class="charts-display">
                    <trendChart width='100%' height='100%' id="trendChart1" :option='pieWorkGotCount'></trendChart>
                </div>
            </div>
        </echartsLayout>
    </div>
</template>

<script>
    import { mapState, mapActions, mapGetters } from 'vuex';
    import echartsLayout from 'components/TableLayout/echartsLayout'; 
    import trendChart from 'components/Charts/trendChart';
    import moment from 'moment';
    export default{
        components: { echartsLayout, trendChart},
        data() {
            return {
                formState: false,
                dataListState: false,
                eCharts1State: false,
                eCharts2State: false,
                eCharts3State: false,
                chartsListState: true,
                tableState: false,
               
               
                selectData: 'peoplea',
                formInline: {
                    time: ''
                },
                loading1: true,
                loading2: true,
                loading3: true,
                AnnounceList: [],
                listQuery: {// 分页
                    page: 1,
                    total: 0
                },
                timeArrs: [
                    {timeName: '近30天', timeId: ''},
                    {timeName: '近12个月', timeId: '1'}
                ],
                totoleAssignPer: 0, // 布置作业总人数
                totoleAssignNum: 0, // 布置作业总次数
                totoleAssignPerTitle: '布置总人数', // 标题（没有返回就默认布置总人数）
                totoleAssignNumTitle: '布置总次数', // 标题（没有返回就默认布置总次数）

                // 布置/提交作业汇总数据
                pieWorkCount: {},
                // 布置题库作业top10
                pieWorkGotCount: {}
            }
        },
        computed: {
            ...mapState({
                config: state => state.config.table
            }),
            ...mapGetters([
                'uid'
            ])
        },
        created() {
            this.getHomeWork();
            this.getTop10();
           
        },
        methods: {
            // 全局获取行数
            ...mapActions(['ChangePageSize']),
            submit() {
                this.getHomeWork();
                this.getTop10();
            },
            getHomeWork() {
                this.loading1=true;
                this.loading2=true;
                let currentDate=moment(new Date()).add(-1, 'days').format('YYYY-MM-DD');// 当前年月日
                let currentMonth=moment(new Date()).format('YYYY-MM-DD');// 当前月
                let beforeDate=moment(new Date()).add(-30, 'days').format('YYYY-MM-DD');// 近30天
                let beforeMonth=moment(new Date()).add(-1, 'year').format('YYYY-MM-DD');// 近12月
                let unit= this.formInline.time==''?'day':'month';// 按月查还是按天
                let from_date= this.formInline.time==''?beforeDate:beforeMonth;// 按月查还是按天
                let to_date= this.formInline.time==''?currentDate:currentMonth;// 按月查还是按天
                let aggregator='unique';// 人数
                let event_name='assignWork';// 布置
                let inforSent={
                    query: {
                        'measures': [
                            {
                                event_name, 
                                aggregator
                            }
                        ],
                        unit, 
                        'sampling_factor': 64,
                        from_date, 
                        to_date, 
                        'tType': 'n', 'ratio': 'n',
                        'approx': false,
                        'axis_config': {
                            'isNormalize': false, 'left': [], 'right': []}, 'filter': {},
                        'detail_and_rollup': true, 'use_cache': true, 'request_id': 1515661490715
                    },
                    totleOrNot: true, // 标志着是作业布置总数 还是下面两个 题库作业总数统计 课外作业总数统计（后者加by_fields）true代表总布置
                    which: 'totle',
                    query_id: '61',
                    real_time: false,
                    dontKnow: true,
                    type: 'bar'// 柱状图
                }
                this.$store.dispatch('getQuery', inforSent).then((data) => {// 布置人数 61（总人数,针对老师）
                    this.totoleAssignPer=data.data.rollup_result.rows[0].values[0][0]?data.data.rollup_result.rows[0].values[0][0]:'暂无';// 布置总人数
                    inforSent.query.measures[0].aggregator='general';
                    inforSent.query_id='60';
                    this.$store.dispatch('getQuery', inforSent).then((data) => {// 布置次数 60（总次数）
                        this.loading1=false;
                        this.totoleAssignNum=data.data.rollup_result.rows[0].values[0][0]?data.data.rollup_result.rows[0].values[0][0]:'暂无';// 布置总人数
                    }).catch(e => {
                        // this.loading1=false;
                    });
                });
                inforSent={
                    query: {
                        'measures': [{'event_name': 'submitWork', 'aggregator': 'unique'}],
                        unit, 
                        'filter': {}, 
                        'by_fields': ['event.submitWork.workType', 'event.submitWork.loginEnd'],
                        'sampling_factor': 64,
                        from_date, 
                        to_date, 
                        'tType': 'n', 'ratio': 'n', 'approx': false, 'axis_config': {'isNormalize': false, 'left': [], 'right': []}, 'detail_and_rollup': true, 'use_cache': false,
                        'request_id': 1515766077955
                    },
                    query_id: '64',
                    real_time: false,
                    type: 'bar'// 柱状图
                };
                // 人数（家长提交总人数，学生提交总人数）
                this.$store.dispatch('getQuery', inforSent).then((data) => {// 64
                    let getData=data.data.rollup_result.rows;
                    let parData=[];
                    let stuData=[];
                    let totleData=[];
                    let parSubPer='';// 家长提交总人数
                    let stuSubPer='';// 学生提交总人数
                    getData.forEach(val => {
                        if (val.by_values[0]=='课外作业') {
                            if (val.by_values[1]=='家庭端家长账号') {// 家长提交人数
                                parSubPer=val.values[0][0]
                            }
                            if (val.by_values[1]=='家庭端学生账号') {
                                stuSubPer=val.values[0][0]
                            }
                        }
                    })


                    // 次数   查提交次数 家长和学生的次数
                    inforSent.query.measures[0].aggregator='general';
                    inforSent.query_id='64';
                    this.$store.dispatch('getQuery', inforSent).then((data) => {// 64
                        this.loading2=false;
                        let parSubNum='';// 家长提交总次数
                        let stuSubNum='';// 学生提交总次数
                        getData.forEach(val => {
                            if (val.by_values[0]=='课外作业') {
                                if (val.by_values[1]=='家庭端家长账号') {
                                    parSubNum=val.values[0][0]
                                }
                                if (val.by_values[1]=='家庭端学生账号') {
                                    stuSubNum=val.values[0][0]
                                }
                            }
                        })
                        parData.push(parSubPer);
                        parData.push(parSubNum);
                        stuData.push(stuSubPer);
                        stuData.push(stuSubNum);
                        totleData.push(parData[0]+stuData[0]);
                        totleData.push(parData[1]+stuData[1]);
                        this.pieWorkCount={
                            tooltip: {
                                trigger: 'axis'
                            },
                            legend: {
                                data: ['总人数', '家长', '学生']
                            },
                            grid: {
                                left: '3%',
                                right: '4%',
                                bottom: '3%',
                                containLabel: true
                            },
                            xAxis: {
                                type: 'category',
                                data: ['提交人数', '提交次数']
                            },
                            yAxis: {
                                type: 'value',
                                boundaryGap: [0, 0.01]
       
                            },
                            series: [
                                {
                                    name: '总人数',
                                    type: 'bar',
                                    color: ['#2EC7C9'],
                                    data: totleData// 提交人数总人数 提交次数总数
                                },
                                {
                                    name: '家长',
                                    type: 'bar',
                                    color: ['#5AB1EF'],
                                    data: parData
                                },
                                {
                                    name: '学生',
                                    color: ['#B6A2DE'],
                                    type: 'bar',
                                    data: stuData
                                }
                            ]
                        }
                    }).catch(e => {
                        // this.loading2=false;
                    })
                })
            },
          
                // 前10
            getTop10() {
                this.loading3=true;
                let currentDate=moment(new Date()).add(-1, 'days').format('YYYY-MM-DD');// 当前年月日
                let currentMonth=moment(new Date()).format('YYYY-MM-DD');// 当前月
                let beforeDate=moment(new Date()).add(-30, 'days').format('YYYY-MM-DD');// 近30天
                let beforeMonth=moment(new Date()).add(-1, 'year').format('YYYY-MM-DD');// 近12月
                let unit= this.formInline.time==''?'day':'month';// 按月查还是按天
                let from_date= this.formInline.time==''?beforeDate:beforeMonth;// 按月查还是按天
                let to_date= this.formInline.time==''?currentDate:currentMonth;// 按月查还是按天
                // 2018-1-22 扣扣发来重配的
                let query={
                    'measures': [{'event_name': 'assignWork', 'aggregator': 'general'}], 
                    unit, 
                    'filter': {
                        'conditions': [{'field': 'event.assignWork.workType', 'function': 'equal', 'params': ['课外作业']}]
                    }, 
                    'by_fields': ['user.name'], 
                    'sampling_factor': 64, 
                    from_date,
                    to_date,
                    'tType': 'n', 'ratio': 'n', 'approx': false, 
                    'axis_config': {'isNormalize': false, 'left': [], 'right': []}, 'detail_and_rollup': true, 'use_cache': true, 
                    'request_id': 1516616054725
                };
                let inforSent={
                    query,
                    query_id: '97',
                    real_time: false,
                    dontKnow: true,
                    innerOrOut: '', // 默认一个环的饼图
                    type: 'pie'// 柱状图
                };
                this.$store.dispatch('getQuery', inforSent).then((data) => {// 布置人数 61
                     // 布置题库作业top10
                    //  自己排出前10名
                    this.loading3=false;
                    let dataList=data.pieList;// 含有全部的 可能是100条，排序出前10名
                    for (let i=0;i<dataList.length;i++) {// 从小到达排序
                        for (let j=i+1;j<dataList.length;j++) {
                            if (dataList[i].value>dataList[j].value) {
                                let value=dataList[i].value;
                                dataList[i].value=dataList[j].value;
                                dataList[j].value=value;
                                let name=dataList[i].name;
                                dataList[i].name=dataList[j].name;
                                dataList[j].name=name;
                            }
                        }
                    }
                    // 然后截取前10
                    if (dataList.length>=10) {
                        dataList=dataList.slice(0, 10);
                    } else {
                        dataList.slice(0, dataList.length);
                    }
                    // 获取前10个name legend
                    let legendData=[];
                    dataList.forEach((val, index) => {
                        if (index<=10) {
                            legendData.push(val.name)
                        }
                    });
                    this.pieWorkGotCount={
                        tooltip: {
                            trigger: 'item',
                            formatter: '{a} <br/>{b} : {c} ({d}%)'
                        },
                        legend: {
                            orient: 'vertical',
                            left: 'left',
                            data: legendData
                        },
                        series: [
                            {
                                name: '访问来源',
                                type: 'pie',
                                radius: '55%',
                                center: ['50%', '60%'],
                                data: dataList,
                                itemStyle: {
                                    emphasis: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                }
                            }
                        ]
                    }
                   
                }).catch(e => {
                    //  this.loading3=false;
                });
            },
            
             // 分页
            handleSizeChange(val) {
                this.listQuery.page = 1;
                this.loading = true;
                this.ChangePageSize(val);
                this.searchFetchData();
            },
            handleCurrentChange(val) {
                this.loading = true;
                this.listQuery.page = val;
                this.searchFetchData();
            },
            sortChange({ column, prop, order }) {
            // "maxCount" "ascending"升序
            // "maxCount" "descending"降序
            // “sequencingType”: “排序类型 （0.售出数量 1.库存数量 2.创建时间）”,
            // “sequencingStatus”: “排序状态 (0.升序 1.降序)”
            // console.log(prop, order, '999')
            // this.sequencingType=prop=='maxCount'?'0':prop=='remainCount'?'1':prop=='createTime'?'2':'';
            // this.sequencingStatus=order=='ascending'?'0':order=='descending'?'1':'';
            // this.searchFetchData(this.sequencingType, this.sequencingStatus)
            }
        }
    }
</script>
<style lang="scss" scoped>
.echartsLayout-content .data-list .data-item .item .title {
    margin-left: 200px !important;
    margin-top: 70px;
}
.echartsLayout-content .data-list .data-item .item .data {
    margin-left: 201px;
    margin-top: 44px;
}
</style>
